package net.adriana.dao;

import java.sql.ResultSet;
import java.util.List;

import net.adriana.Fac;
import net.adriana.bean.Column;
import net.adriana.bean.Schema;
import net.adriana.bean.Table;
import net.adriana.esaytool.Logger;
import net.adriana.esaytool.util.BeanUtil;
import net.adriana.esaytool.util.MetaDataUtil;

public class SchemaDao {
	public Schema getSchema(String schemaName)throws Exception{
		Schema schema = new Schema();
		schema.setSchemaName(schemaName);
		schema.setTables(getAllTables(schema));
		return schema;
	}
	public Table[] getAllTables(Schema schema)throws Exception{
		ResultSet rs = MetaDataUtil.getTables(null, null);
		@SuppressWarnings("unchecked")
		List<Table> tables = (List<Table>)BeanUtil.listFill(rs, Table.class);
		if(tables!=null)Logger.log(Logger.DEBUG, "填充Table集合成功");
		else Logger.log(Logger.ERROR, "填充Table集合失败");
		for (Table table : tables) {
			table.setSchema(schema);
			table.setCols(getCols(table.getTableName()));
		}
		rs.close();
		MetaDataUtil.closeConnection();
		Table[] t = (Table[])tables.toArray(new Table[0]);
		return t;
	}
	
	public Column[] getCols(String tableName) throws Exception{
		ResultSet rs = MetaDataUtil.getColumns(tableName, null);
		@SuppressWarnings("unchecked")
		List<Column> cols = (List<Column>)BeanUtil.listFill(rs, Column.class);
		if(cols!=null)Logger.log(Logger.DEBUG, "填充Column集合成功");
		else Logger.log(Logger.ERROR, "填充Column集合失败");
		rs.close();
		MetaDataUtil.closeConnection();
		Column[] c = (Column[])cols.toArray(new Column[0]);
		return c;
	}
	
	public boolean login(String schemaName,String user,String password){
		if(schemaName == null) schemaName = "db_forum";
		if(user == null) user = "root";
		if(password == null) password = "123";
		MetaDataUtil.USER = user;
		MetaDataUtil.PASSWORD = password;
		try {
			Fac.schema = getSchema(schemaName);
			Fac.init();
			if(MetaDataUtil.getConnection()!=null){
				MetaDataUtil.closeConnection();
				return true;
			}
		} catch (Exception e) {
			return false;
		}
		return false;
	}
}
